﻿using Castle.DynamicProxy;
using Framework.LinkTrackingLog.AI_Deepseek;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Framework.LinkTrackingLog.MyTest
{
    /// <summary>
    /// Action过滤器
    /// </summary>
    internal class MethodMonitoringActionFilter : IActionFilter
    {
        /// <summary>
        /// 监控服务
        /// </summary>
        public IMethodMonitoringService methodMonitoringService { get; }
        /// <summary>
        /// Action过滤器
        /// </summary>
        /// <param name="context">监控服务</param>
        public MethodMonitoringActionFilter(IMethodMonitoringService context)
        {
            methodMonitoringService = context;
        }
        /// <summary>
        /// 监控特性
        /// </summary>
        public MethodMonitoringAttribute? attribute { get; set; }
        /// <summary>
        /// 方法执行后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //判断当前请求的Action端点是否标记了MethodMonitoringAttribute特性
            if (attribute?.Monitor ?? true)
            {
                if (context.Exception != null)
                {
                    methodMonitoringService.Execute(context.Exception);
                }
                else
                {
                    //结束监控
                    methodMonitoringService.StopMonitoring(context.ActionDescriptor.DisplayName, context.Controller.GetType().Name);
                }
            }
        }
        /// <summary>
        /// 方法执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //判断当前请求的Action端点是否标记了MethodMonitoringAttribute特性
            //这包括直接应用在Action方法上或继承自控制器类的特性
            attribute = context.ActionDescriptor.EndpointMetadata.FirstOrDefault(m => m is MethodMonitoringAttribute) as MethodMonitoringAttribute;
            if (attribute?.RecordInput ?? false)
            {
                //获取参数

            }
            //判断当前请求的Action端点是否标记了MethodMonitoringAttribute特性
            if (attribute?.Monitor ?? true)
            {
                //开启监控
                methodMonitoringService.StartMonitoring(context.ActionDescriptor.DisplayName, context.Controller.GetType().Name);
            }
        }
    }
}
